package com.blt.govdata.core.web;

import com.blt.govdata.core.constants.Constants;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

import static java.util.Objects.nonNull;


/**
 * 配置用户登录拦截器（Session）
 * */
@Configuration
public class LoginWebMvcConfigurer extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptorAdapter() {

            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                if (handler instanceof HandlerMethod) {

                    final boolean login = nonNull(request.getSession().getAttribute(Constants.CURRENT_USER));
                    if (!login) {
                        final HandlerMethod handlerMethod = (HandlerMethod) handler;
                        Arrays.stream(handlerMethod.getMethodParameters())
                                .filter(p -> p.hasParameterAnnotation(SessionAttribute.class))
                                .map(p -> p.getParameterAnnotation(SessionAttribute.class))
                                .filter(SessionAttribute::required)
                                .findFirst().ifPresent(e -> {
                            if (!login) throw new NeedLoginException("用户需要登录");
                        });
                    }
                }
                return true;
            }
        }).addPathPatterns("/**").excludePathPatterns("/login*");
    }
}
